package com.zeedev.flyingsaucer.beers.downloaders;

import android.content.Context;
import android.widget.Toast;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.name.Named;
import com.zeedev.flyingsaucer.beers.activities.home.impl.HomeModel;
import com.zeedev.flyingsaucer.global.UfoClubApp;
import mobi.zeedev.flyingsaucer.common.CredentialsModule.interfaces.IPreferenceCredentials;
import mobi.zeedev.flyingsaucer.common.WebLinkModule.impl.UfoClubClientImpl;
import roboguice.util.Ln;
import roboguice.util.RoboAsyncTask;

/**
 * User: James Johnson
 * Date: Oct 29, 2010
 * Time: 11:13:11 PM
 */
public class MemberIdDownloader extends RoboAsyncTask {

    @Inject
    Context mContext;

    @Inject
    UfoClubApp app;

    @Inject
    @Named("autoIPreferenceCredentials")
    Provider<IPreferenceCredentials> credentials;

    private HomeModel model;

    @Inject
    public MemberIdDownloader(HomeModel model) {
        this.model = model;
    }

    @Inject
    UfoClubClientImpl beerLink;

    @Override
    public Object call() throws Exception {

        Integer memberId = beerLink.getMemberId();

        return memberId;
    }


    @Override
    protected void onFinally() throws RuntimeException {
        super.onFinally();
        model.setRefreshing(false);
    }

    @Override
    protected void onException(Exception e) throws RuntimeException {
        super.onException(e);
        Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onSuccess(Object o) throws Exception {
        super.onSuccess(o);

        Integer memberId = (Integer) o;

        if (memberId == null) {
            Ln.w("Member Id could not be found.");
            if (credentials.get().getCredentials().getMemberId() > 0) {
                memberId = credentials.get().getCredentials().getMemberId();
                Ln.w("Using existing member id in credentials.");
            } else {
                memberId = 0;
                Ln.w("Using stub member id of 0.");
            }
//            Toast.makeText(mContext,"There was an error updating your member id.", Toast.LENGTH_SHORT).show();
        }


        credentials.get().getCredentials().setMemberId(memberId);
        if (credentials.get().getCredentials().getUfoRemember()) {
            app.setLastMember(memberId);
        }
        credentials.get().bindToPreferences();
//        Toast.makeText(mContext, "Your memeber id has been updated.", Toast.LENGTH_SHORT).show();

    }

    @Override
    protected void onPreExecute() throws Exception {
        super.onPreExecute();
        model.setRefreshing(true);
    }
}
